var mysql = require('mysql');

var myDB = module.exports = {};

//dbInfo.dbType host port user password database
var getConn = function (dbInfo) {
    var conn;
    dbInfo = dbInfo || {};
    switch (dbInfo || dbInfo.dbType || 'mysql') {
        case 'sqlite':
            //conn = getConn_mysql(dbInfo);
            break;

        case 'oracle':
            break;

        case 'sqlserver':
            break;

        default:
            //mysql
            conn = getConn_mysql(dbInfo);

    }
    return conn;
}

var getConn_mysql = function (dbInfo) {
    var conn = mysql.createConnection({
        host: dbInfo.host || 'localhost',
        port: dbInfo.port || 3306,
        user: dbInfo.user || 'root',
        password: dbInfo.password || 'root',
        database: dbInfo.database || 'test',
        multipleStatements: true
    });
    return conn;
}

//执行一条sql语句,执行一批sql语句,执行一条带pms的sql,执行带多条pms的sql


myDB.exeSqls = function (dbInfo, sqls, pms, fn) {
    pms = pms || [];
    var conn = getConn(dbInfo);
    conn.connect();
    if (sqls.indexOf(';') > -1) {
        //表示多条sql语句
        console.log(sqls, pms);
        conn.query(sqls, function (err, data) {
            conn.end();
            fn(err, data);
        });
    } else if (pms.length > 0 && typeof pms[0] == 'object' && (pms[0]).constructor == Array) {
        //表示插入多行数据
        console.log(sqls, pms);
        dgSqls(conn, sqls, pms, 0, function (err, data) {
            conn.end();
            fn(err, data);
        })

    } else {
        //表示执行带参数的一条sql语句
        console.log(sqls, pms);
        conn.query(sqls, pms, function (err, data) {
            conn.end();
            fn(err, data);
        });
    }
}

//递归,执行一次插入多行数据的
var dgSqls = function (conn, sql, pms, i, fn) {
    var pm = pms[i]
    conn.query(sql, pm, function (err, data) {
        if (i < pms.length - 1) {
            dgSqls(conn, sql, pms, i + 1, fn)
        } else {
            fn(err, pms.length);
        }
    })
}